﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.Threading;

public partial class SystemManage_ClientList : BasePage
{
    ISyClientHandler clientManage = new SyClientHandler();
    DataBase db = new DataBase();
    ISystemHandler systemManage = new SystemHandler();
    IRolePurviewHandler userManage = new RolePurviewHandler();

    private static bool isUpdate = false;
    private static bool isDel = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!strPermission.Contains("1034"))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                else
                {
                    //判断用户有没有添加客户权限
                    if (strPermission.Contains("1035"))
                    {
                        lblClientAdd.Visible = true;
                        lblImport.Visible = true;
                        Button2.Visible = true;
                    }
                    else
                    {
                        lblClientAdd.Visible = false;
                        lblImport.Visible = false;
                        Button2.Visible = false;
                    }
                    //判断用户有没有修改客户权限
                    if (strPermission.Contains("1036"))
                    {
                        isUpdate = true;
                    }
                    else
                    {
                        isUpdate = false;
                    }
                    //判断用户有没有删除客户权限
                    if (strPermission.Contains("1037"))
                    {
                        isDel = true;
                    }
                    else
                    {
                        isDel = false;
                    }

                }
            }

            ViewState["OrderBy"] = "Status";
            ViewState["Accending"] = "desc";
            FillClientType();
            dataBind();
        }
    }

    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        sqlstr = "";
        if (ViewState["Value"] != null)
        {
            if (ViewState["Name"].ToString().ToLower() == "cnshortname")
            {
                list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                list.Add(new SqlParameter("@HKShortName", ViewState["Value"].ToString()));
                list.Add(new SqlParameter("@ENGShortName", ViewState["Value"].ToString()));
                sqlstr += " and ( " + ViewState["Name"].ToString() + " like '%' +  @ColumnName + '%' or ENGShortName like '%' +  @ENGShortName + '%' or HKShortName like '%' +  @HKShortName + '%')";
            }
            else if (ViewState["Name"].ToString().ToLower() == "cnname")
            {
                list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                list.Add(new SqlParameter("@HKName", ViewState["Value"].ToString()));
                list.Add(new SqlParameter("@ENGName", ViewState["Value"].ToString()));
                sqlstr += " and ( " + ViewState["Name"].ToString() + " like '%' +  @ColumnName + '%' or ENGName like '%' +  @ENGName + '%' or HKName like '%' +  @HKName + '%')";

            }
            //else if (ViewState["Name"].ToString().ToLower() == "title")
            //{
            //    list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
            //    list.Add(new SqlParameter("@HKTitle", ViewState["Value"].ToString()));
            //    list.Add(new SqlParameter("@ENGTitle", ViewState["Value"].ToString()));
            //    sqlstr += " and ( " + ViewState["Name"].ToString() + " like '%' +  @ColumnName + '%' or ENGTitle like '%' +  @ENGTitle + '%' or HKTitle like '%' +  @HKTitle + '%')";

            //}
        }

        if (ViewState["Type"] != null)
        {
            list.Add(new SqlParameter("@CType",ViewState["Type"]));
            sqlstr += " and PKID in(select ClientID from Sy_ClientType where SyCodeID=@CType)";
        }
        if (ViewState["Status"] != null)
        {
            list.Add(new SqlParameter("@Status", ViewState["Status"].ToString()));
            sqlstr += " and Status = @Status";
        }

        sqlstr += " and Status !=" + Enums.ClientStatus.Delete.ToString("d");

        parms = list.ToArray();
    }


    private void dataBind()
    {
        string sqlStr = "SELECT S.* FROM Sy_Client as S where 1=1 ";
        SqlParameter[] parms = null;
        string clause = string.Empty;
        ProcessParms(ref clause, ref parms);
        sqlStr += clause ;

        DataTable dt = clientManage.GetClientList(sqlStr, parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvClientList.DataSource = view;
        gvClientList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }
    }

    private void FillClientType()
    {
       DataTable dt= clientManage.GetClientTypeList();
       ddlType.DataSource = dt;

       if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
       {
           ddlType.DataTextField = "ENGName";
       }
       else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
       {
           ddlType.DataTextField = "HKName";
       }
       else
       {
           ddlType.DataTextField = "Name";
       }
       ddlType.DataValueField = "PKID";
       ddlType.DataBind();
       ddlType.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));
       
    }

    protected void gvClientList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvClientList.PageIndex = e.NewPageIndex;
        dataBind();
    }
    protected void gvClientList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Del")
        {
            Sy_ClientQuery query = clientManage.GetClient(int.Parse(e.CommandArgument.ToString()));
            if (query != null)
            {
                query.Status = int.Parse(Enums.ClientStatus.Delete.ToString("d"));
                if (!clientManage.ClientDelete(query))
                {
                    Jscript.AlertInAjax(Resources.Messages.DeleteFailed, UpdatePanel1);
                }
            }           
        }

        if (e.CommandName == "status")
        {

            Sy_ClientQuery query = clientManage.GetClient(int.Parse(e.CommandArgument.ToString()));
            if (query != null)
            {
                if (query.Status == int.Parse(Enums.ClientStatus.INVALID.ToString("d")))
                {
                    query.Status = int.Parse(Enums.ClientStatus.VALID.ToString("d"));
                }
                else
                {
                    query.Status = int.Parse(Enums.ClientStatus.INVALID.ToString("d"));

                }
                if (!clientManage.ClientDelete(query))//修改状态
                {
                    Jscript.AlertInAjax(Resources.Messages.UpdateFailed, UpdatePanel1);
                }
            }
        }

        dataBind();
    }
    protected void gvClientList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {

        if (txtName.Text != string.Empty)
        {
            ViewState["Value"] = txtName.Text.Trim();
            ViewState["Name"] = ddlColumnName.SelectedValue;
        }
        else
        {
            ViewState["Value"] = null;
            ViewState["Name"] = null;
        }

        if (ddlType.SelectedValue  != "0")
        {
            ViewState["Type"] = ddlType.SelectedValue;
        }
        else
        {
            ViewState["Type"] = null;
        }    

        if (radAll.Checked)
        {
            ViewState["Status"] = null;
        }
        else if (radYes.Checked)
        {
            ViewState["Status"] = "1";
        }
        else
        {
            ViewState["Status"] = "0";
        }
        dataBind();

    }
    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvClientList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvClientList.PageCount)
            {
                this.gvClientList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvClientList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }
    protected void gvClientList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton btnDel = (LinkButton)e.Row.FindControl("lbtnDel");
            Label lblEdit = (Label)e.Row.FindControl("lblEdit");

            if (isUpdate)
            {
                lblEdit.Visible = true;
            }
            else
            {
                lblEdit.Visible = false;
            }

            if (isDel)
            {
                btnDel.Visible = true;
            }
            else
            {
                btnDel.Visible = false;
            }

            Label lblCNName = (Label)e.Row.FindControl("lblCNName");
            Label lblENName = (Label)e.Row.FindControl("lblENName");
            Label lblHKName = (Label)e.Row.FindControl("lblHKName");
            //Label lblCNTitle = (Label)e.Row.FindControl("lblCNTitle");
            //Label lblENTitle = (Label)e.Row.FindControl("lblENTitle");
            //Label lblHKTitle = (Label)e.Row.FindControl("lblHKTitle");

            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
            {
                lblENName.Visible = true;
               // lblENTitle.Visible = true;
                lblCNName.Visible = false;
                lblHKName.Visible = false;
               // lblCNTitle.Visible = false;
               // lblHKTitle.Visible = false;
            }
            else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                lblENName.Visible = false;
              //  lblENTitle.Visible = false;
                lblCNName.Visible = false;
                lblHKName.Visible = true;
               // lblCNTitle.Visible = false;
               // lblHKTitle.Visible = true;
            }
            else
            {
                lblENName.Visible = false;
               // lblENTitle.Visible = false;
                lblCNName.Visible = true;
                lblHKName.Visible = false;
                //lblCNTitle.Visible = true;
                //lblHKTitle.Visible = false;
            }


        }
    }

    public string GetPlace(object id)
    {
        return systemManage.GetPlace(id);
    }

    public string GetTypeName(int typeID)
    {
        return clientManage.GetTypeNameByTypeID(typeID);
    }

    public string GetUserName(object id)
    {
        return systemManage.GetUserName(id);
    }
   
    private DataTable Export()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("CNShortName");
        dt.Columns.Add("HKShortName");
        dt.Columns.Add("ENShortName");
        dt.Columns.Add("CNName");
        dt.Columns.Add("HKName");
        dt.Columns.Add("ENName");
        dt.Columns.Add("CNAddress");
        dt.Columns.Add("HKAddress");
        dt.Columns.Add("ENAddress");
        dt.Columns.Add("Email");
        dt.Columns.Add("Website");
        dt.Columns.Add("PShiper");
        dt.Columns.Add("LocalBP");
        dt.Columns.Add("Place");

        dt.Columns.Add("CompanyBP");
        dt.Columns.Add("MVendorCode");
        dt.Columns.Add("HVendorCode");
        dt.Columns.Add("ToYantian");    
        dt.Columns.Add("ToShekou");
        dt.Columns.Add("GPSWebsite");

        dt.Columns.Add("Type");
        dt.Columns.Add("LinkMan");
        dt.Columns.Add("Remark");
        dt.Columns.Add("Status");

        string sqlStr = "SELECT S.* FROM Sy_Client as S where 1=1 ";
        SqlParameter[] parms = null;
        string clause = string.Empty;
        ProcessParms(ref clause, ref parms);
        sqlStr += clause;
        DataTable dtC = clientManage.GetClientList(sqlStr, parms);
        DataTable dtType = new DataTable();
        DataTable dtLinkMan = new DataTable();
        

        if (dtC != null && dtC.Rows.Count > 0)
        {
            for (int i = 0; i < dtC.Rows.Count; i++)
            {
                string typeName = string.Empty;//保存分类名称
                string placeName = string.Empty;//保存地点名称
                string linkMan = string.Empty;//联络人资料列表
                string compUserName = string.Empty;//本公司业务员

                dtType = clientManage.GetClientTypeByID(int.Parse(dtC.Rows[i]["PKID"].ToString()));
                if (dtType != null && dtType.Rows.Count > 0)
                {
                    for (int t = 0; t < dtType.Rows.Count; t++)//获取客户分类名列表
                    {
                        if (t != dtType.Rows.Count - 1)
                        {
                            typeName += GetTypeName(int.Parse(dtType.Rows[t]["SyCodeID"].ToString())) + ",";
                        }
                        else
                        {
                            typeName += GetTypeName(int.Parse(dtType.Rows[t]["SyCodeID"].ToString()));
                        }
                    }
                }

                placeName = GetPlace(dtC.Rows[i]["PlaceID"].ToString());//地点名称

                dtLinkMan = clientManage.GteLinkMansByClientID(int.Parse(dtC.Rows[i]["PKID"].ToString()));
                if (dtLinkMan != null && dtLinkMan.Rows.Count > 0)
                {
                    for (int l = 0; l < dtLinkMan.Rows.Count; l++)
                    {
                        linkMan += dtLinkMan.Rows[l]["LinkMan"].ToString() + "," + dtLinkMan.Rows[l]["TelNo"].ToString() + "," + dtLinkMan.Rows[l]["MPhone"].ToString() + ",";
                        linkMan += dtLinkMan.Rows[l]["Fax"].ToString() + "," + dtLinkMan.Rows[l]["Email"].ToString() + "," + dtLinkMan.Rows[l]["Position"].ToString() + ",";
                        linkMan += dtLinkMan.Rows[l]["Address"].ToString() + "," + dtLinkMan.Rows[l]["Remark"].ToString();
                        if (l != dtLinkMan.Rows.Count - 1)
                        {
                            linkMan += ";";
                        }
                    }
                }


                UsersQuery users = userManage.GetUsers(int.Parse(dtC.Rows[i]["CompanyBP"].ToString()));
                if (users != null)
                {
                    compUserName = users.LoginID;
                }

                dt.Rows.Add(new string[] {
                     dtC.Rows[i]["CNShortName"].ToString(),
                     dtC.Rows[i]["HKShortName"].ToString(),
                     dtC.Rows[i]["ENGShortName"].ToString(),

                     dtC.Rows[i]["CNName"].ToString(),
                     dtC.Rows[i]["HKName"].ToString(),
                     dtC.Rows[i]["ENGName"].ToString(),

                     dtC.Rows[i]["CNAddress"].ToString(),
                     dtC.Rows[i]["HKAddress"].ToString(),
                     dtC.Rows[i]["ENGAddress"].ToString(),
                     dtC.Rows[i]["Email"].ToString(),
                     dtC.Rows[i]["WebSite"].ToString(),
                     dtC.Rows[i]["PShiper"].ToString(),
                     dtC.Rows[i]["LocalBP"].ToString(),
                     placeName,
                     compUserName,
                     dtC.Rows[i]["MVendorCode"].ToString(),
                     dtC.Rows[i]["HVendorCode"].ToString(),
                     dtC.Rows[i]["ToYantian"].ToString(),
                     dtC.Rows[i]["ToShekou"].ToString(),
                     dtC.Rows[i]["GPSWebsite"].ToString(),
                     typeName,
                     linkMan,
                     dtC.Rows[i]["Remark"].ToString(),
                     dtC.Rows[i]["Status"].ToString()
                });
            }
        }
        return dt;
        
    }

    //导出Excel 
    protected void Button2_Click(object sender, EventArgs e)
    {

        BackupToExcel.ExportExcel(Export(), "Client");
    }

}
